#!/bin/bash
# Docker镜像构建脚本

set -e  # 遇到错误立即退出

echo "🚀 开始构建边侧节点AI服务系统Docker镜像..."

# 镜像配置
IMAGE_NAME="edge-ai-service"
VERSION=${1:-"latest"}
REGISTRY=${2:-"localhost"}

FULL_IMAGE_NAME="${REGISTRY}/${IMAGE_NAME}:${VERSION}"

echo "📦 镜像信息:"
echo "  - 镜像名称: ${IMAGE_NAME}"
echo "  - 版本标签: ${VERSION}"
echo "  - 完整名称: ${FULL_IMAGE_NAME}"
echo ""

# 检查Docker是否运行
if ! docker info >/dev/null 2>&1; then
    echo "❌ Docker未运行或无法访问，请检查Docker服务状态"
    exit 1
fi

# 清理旧的构建缓存（可选）
if [ "$3" = "--clean" ]; then
    echo "🧹 清理Docker构建缓存..."
    docker builder prune -f
fi

# 构建镜像
echo "🔨 开始构建镜像..."
docker build \
    --tag "${FULL_IMAGE_NAME}" \
    --tag "${REGISTRY}/${IMAGE_NAME}:latest" \
    --build-arg BUILD_DATE="$(date -u +'%Y-%m-%dT%H:%M:%SZ')" \
    --build-arg VCS_REF="$(git rev-parse --short HEAD 2>/dev/null || echo 'unknown')" \
    -f Dockerfile \
    ..

# 检查构建结果
if [ $? -eq 0 ]; then
    echo "✅ 镜像构建成功！"
    echo ""
    echo "📋 镜像详情:"
    docker images "${REGISTRY}/${IMAGE_NAME}" | head -2
    echo ""
    echo "🎯 下一步操作:"
    echo "  启动容器: ./docker-run.sh"
    echo "  推送镜像: docker push ${FULL_IMAGE_NAME}"
    echo "  查看镜像: docker inspect ${FULL_IMAGE_NAME}"
else
    echo "❌ 镜像构建失败！"
    exit 1
fi 